package ru.niir.goodfil.ui;

import static ru.niir.goodfil.utils.Utils.s;

import javax.faces.model.SelectItem;
import java.util.List;
import java.util.ArrayList;

import static org.apache.commons.lang.StringUtils.isBlank;
import org.apache.log4j.Logger;

/**
 * Бин окна для работы с оригинальными номерами товаров
 */
public class OesBean extends PageBean
{
    private static final Logger logger = Logger.getLogger(OesBean.class);

    private String goodCode;
    private String input;
    private List<String> selectedOes = new ArrayList<String>();

    public List<SelectItem> getOes()
    {
        if (isBlank(goodCode)) return new ArrayList<SelectItem>();

        logger.debug("getOes: " + goodCode);

        List<SelectItem> result = new ArrayList<SelectItem>();
        for (String oe : gf().getOesForGood(goodCode))
            result.add(new SelectItem(oe, oe));
        logger.debug("result: " + result.size());
        return result;
    }

    public String getGoodCode()
    {
        return goodCode;
    }

    public void setGoodCode(String goodCode)
    {
        logger.debug("goodCode --> " + goodCode);
        this.goodCode = s(goodCode);
    }

    public List<String> getSelectedOes()
    {
        return selectedOes;
    }

    public void setSelectedOes(List<String> selectedOes)
    {
        this.selectedOes = selectedOes;
    }

    public void setInput(String input)
    {
        logger.debug("input --> " + input);
        this.input = input;
    }

    public String getInput()
    {
        return input;
    }

    public void insert()
    {
        logger.debug("inserting input: " + input + ", goodCode: " + goodCode);

        try
        {
            gf().addOeForGood(goodCode, input);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void delete()
    {
        logger.debug("deleting goodCode: " + goodCode);

        for (String selectOe : selectedOes)
        {
            try
            {
                logger.debug("  * " + selectOe);
                gf().removeOeForGood(selectOe);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
